package com.hjy.test;


import com.sun.security.ntlm.Server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* serverBootstrap.option(ChannelOption.SO_RCVBUF, 10)
* 影响的底层接收缓冲区（即滑动窗口）大小，
* 仅决定了 netty 读取的最小单位，netty 实际每次读取的一般是它的整数倍
* */
public class StudyServer {
    static final Logger log = LoggerFactory.getLogger(StudyServer.class);
    void  start(){
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.channel(NioServerSocketChannel.class);
            // 调整channel的容量  如果发送数据多了 会出现多次半包
            bootstrap.option(ChannelOption.SO_RCVBUF, 10);
            bootstrap.group(boss, worker);
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel channel) {
                    channel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                    channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            //连接建立的时候会用
                            log.info("connected:{}", ctx.channel());
                            super.channelActive(ctx);
                        }

                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            log.info("disconnect:{}", ctx.channel());
                            super.channelInactive(ctx);
                        }
                    });
                }
            });
            ChannelFuture channelFuture = bootstrap.bind(8080);
            log.info("{} binding...", channelFuture.channel());
            channelFuture.sync();
            log.info("{} bound...", channelFuture.channel());
            //关闭channel
            channelFuture.channel().closeFuture().sync();
        }catch (InterruptedException e){
            e.printStackTrace();
            log.error("server error ", e);
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
            log.info("stoped");
        }
    }

    public static void main(String[] args) {
        new StudyServer().start();;
    }
}
